<template>
  <div class="sql-parser-container">
    <h2 class="parser-title">SQL解析器</h2>

    <el-form
        ref="sqlForm"
        :model="formData"
        :rules="formRules"
        class="sql-form"
        label-width="120px"
    >
      <!-- 数据库名称输入 -->
      <el-form-item label="数据库名称" prop="baseSQLName">
        <el-input
            v-model="formData.baseSQLName"
            placeholder="请输入数据库名称"
            clearable
        ></el-input>
      </el-form-item>

      <!-- SQL语句输入 -->
      <el-form-item label="SQL语句" prop="sql2">
        <el-input
            v-model="formData.sql2"
            type="textarea"
            :rows="10"
            placeholder="请输入CREATE TABLE等SQL语句"
            clearable
        ></el-input>
        <div class="sql-hint text-xs text-gray-500 mt-1">
          支持标准CREATE TABLE语法，将自动解析表结构并创建
        </div>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button
            type="primary"
            @click="handleSubmit"
            :loading="isLoading"
            class="submit-btn"
        >
          <template #loading>处理中...</template>
          解析并创建表结构
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, ElForm } from "element-plus";
import { useTableSqlService } from "@/api/Table/TableSqlApi.js";

// 导入API服务
const { createTableSql, createTableColumnSql } = useTableSqlService();

// 表单引用
const sqlForm = ref<InstanceType<typeof ElForm>>();

// 加载状态
const isLoading = ref(false);

// 表单数据
const formData = reactive({
  baseSQLName: "",
  sql2: ""
});

// 表单验证规则
const formRules = reactive({
  baseSQLName: [
    { required: true, message: "请输入数据库名称", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "数据库名称只能包含字母、数字和下划线", trigger: "blur" }
  ],
  sql2: [
    { required: true, message: "请输入SQL语句", trigger: "blur" },
    { min: 10, message: "SQL语句不能太短", trigger: "blur" }
  ]
});

// 提交处理
const handleSubmit = async () => {
  // 表单验证
  if (!sqlForm.value) return;

  try {
    await sqlForm.value.validate();
    isLoading.value = true;

    // 创建表
    const response = await createTableSql({
      sql: formData.sql2,
      databaseName: formData.baseSQLName,
    });

    // 创建列
    const response2 = await createTableColumnSql({
      sql: formData.sql2,
      databaseName: formData.baseSQLName,
    });
    // 验证两个请求是否都成功
    if (response && response2) {
      ElMessage.success(`创建成功！请在数据库中搜索：${formData.baseSQLName}`);
      // 重置表单
      sqlForm.value.resetFields();
    } else {
      ElMessage.error("创建过程中发生错误");
    }
  } catch (error: any) {
    // 处理验证失败或API错误
    if (error.name === "ValidationError") {
      return; // 表单验证失败，不显示额外错误
    }

    ElMessage.error(`操作失败：${error.message || "未知错误"}`);
    console.error("SQL处理错误:", error);
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.sql-parser-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.parser-title {
  text-align: center;
  margin-bottom: 20px;
  color: #1f2329;
}

.sql-form {
  margin-top: 15px;
}

.submit-btn {
  width: 100%;
  padding: 10px 0;
  font-size: 16px;
}

.sql-hint {
  line-height: 1.5;
}
</style>
